package com.car.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.car.common.CodeMsg;
import com.car.common.execption.BussiException;
import com.car.common.util.WebUtil;
import com.car.sys.vo.SysUsersVO;

/**
 * @ClassName: LoginIntercepter 
 * @Description: 登录拦截器
 * @author: TiTanLee
 * @date: 2019年11月30日 下午2:43:31
 */
public class LoginIntercepter implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取当前客户
		SysUsersVO user = WebUtil.getCurrentUser();
		// 判断用户是否存在
		if (user != null) {
			return true;
		}
		// 判断是否是Ajax请求，如果是则返回json数据
		String xRequestedWith = request.getHeader("X-Requested-With");
		if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
			throw new BussiException(CodeMsg.LOGIN_TIMEOUT.CODE,CodeMsg.LOGIN_TIMEOUT.MSG);
		}else {
			// 没有登录就跳转到登录页面
		response.sendRedirect(WebUtil.getSelServletContext().getAttribute("cxt") + "/index.html");
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
